package mx.netbrain.dao;

import java.util.List;

import mx.netbrain.model.User;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

public class UserDao extends HibernateUtil {

	private SessionFactory sf = HibernateUtil.getSessionFactory();
	private Transaction t = null;
	private static final Logger logger = Logger.getLogger(UserDao.class);

	public User add(User user) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		session.save(user);
		t.commit();
		return user;
	}

	public User delete(Long id) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		User user = (User) session.load(User.class, id);
		if (null != user) {
			session.delete(user);
		}
		t.commit();
		return user;
	}

	@SuppressWarnings("unchecked")
	public List<User> list() {
		Session session = sf.openSession();
		t = session.beginTransaction();
		List<User> user = null;
		try {
			user = session.createQuery("from User").list();
		} catch (HibernateException e) {
			logger.error("Problema con Hibernate: " + e);
			e.printStackTrace();
			t.rollback();
		}
		t.commit();
		return user;
	}

	public User findById(Long id) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		User user = (User) session.load(User.class, id);
		t.commit();
		return user;
	}

	@SuppressWarnings("unchecked")
	public List<User> findByUsername(String username, String passowrd) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(passowrd);
		Session session = sf.openSession();
		t = session.beginTransaction();
		List<User> userList = null;
		try {
			userList = session.createCriteria(User.class)
					.add(Example.create(user)).list();
		} catch (HibernateException e) {
			logger.error("Problema con Hibernate: " + e);
			e.printStackTrace();
			t.rollback();
		}
		t.commit();
		return userList;
	}
}
